package org.xmonkey.controller.extractor;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.xmonkey.Messages;
import org.xmonkey.controller.extractor.visitors.ResourceVisitor;
import org.xmonkey.util.Log;

/**
 * This class is responsible for gathering the compilation units that
 * compose the project that must be analyzed and visited.
 * Each compilation unit will then be represented as an abstract syntax tree
 * and each node of that tree will be analyzed.
 * @author Jacopo Malnati
 *
 */
public final class ASTProjectParser extends ProjectRelatedJob {
	
	public ASTProjectParser(IProject projectToParse){
		super(Messages.ASTProjectParser_0 + projectToParse.getName(), projectToParse);
		setUpJob();
	}
	
	/**
	 * The job will be long, and provide feedbacks to the user
	 */
	public void setUpJob(){
		setUser(true);
		setPriority(LONG);
	}
	
	/**
	 * Given an user-defined project, start parsing and analyzing it
	 * @param projectToParse the project that must be parsed and analyzed
	 */
	@Override
	protected IStatus run(IProgressMonitor monitor) {
		try {
			// before starting it, we predict how many items we will visit
			TicksPredictorVisitor ticksPredictor = new TicksPredictorVisitor();
			getProject().accept(ticksPredictor);
			monitor.beginTask(Messages.ASTProjectParser_1, ticksPredictor.getNrFiles());
			ResourceVisitor visitor = new ResourceVisitor(monitor, getProject());
			getProject().accept(visitor);
		} catch (Exception e) {
			Log.printError( Messages.ASTProjectParser_2, e);
			return Status.CANCEL_STATUS;
		}
		
		// if the analysis has been canceled, do not set the incomplete model and exit
		if(!monitor.isCanceled()){
			monitor.setTaskName(Messages.ASTProjectParser_3);
			return Status.OK_STATUS;
		} else {
			Log.printInfo(Messages.ASTProjectParser_4 + getProject().getName() + Messages.ASTProjectParser_5,  null);
			return Status.CANCEL_STATUS;
		}
	}
	


}